<template>
  <c-dialog
    v-model="dialogVisible"
    title="问题收录"
    :width="'700px'"
    :before-close="handleClose">
    <el-form :model="form" :rules="rules" class="album-dialog-form" label-position="top" ref="formRef">
      <el-form-item label="问题ID" prop="question_id">
        <el-input v-model="form.question_id" placeholder="请输入问题ID" size="large" />
      </el-form-item>
      <el-form-item label="问题来源" prop="type">
        <el-select v-model="form.type" style="width: 100%;" placeholder="请选择问题来源">
          <el-option label="作者发布" :value="'publish'" />
          <el-option label="作者关注" :value="'follow'" />
          <el-option label="作者回答" :value="'answer'" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #action>
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </template>
  </c-dialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue';
import { type FormRules } from 'element-plus';
import http from '@/utils/http'
import { useMessage } from '@/utils/utils';

/**
 * 实例
 */
interface Props {
  modelValue: boolean
  author_id?: number
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: false
})
const emit = defineEmits(['update:modelValue', 'submit'])

/**
 * 变量
 */
const dialogVisible = computed({
  get () {
    return props.modelValue
  },
  set (val) {
    emit('update:modelValue', val)
  }
})
const form: any = reactive({
  question_id: '',
  type: 'publish',
})
const rules: FormRules = reactive({
  question_id: [
    { required: true, message: '请输入问题id', trigger: ['blur', 'change'] }
  ],
  type: [
    { required: true, message: '请选择问题来源', trigger: ['blur', 'change'] }
  ],
})
// 表单ref
const formRef = ref(null)

/**
 * 回调函数
 */
// 关闭窗口
const handleClose = () => {
  dialogVisible.value = false
}
// 提交
const submit = () => {
  // @ts-ignore
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      http('/author/question/create', {
        question_id: form.question_id,
        type: form.type,
        author_id: props.author_id
      }).then(res => {
        useMessage('收录成功')
        handleClose()
        emit('submit')
      })
    }
  })
}
</script>

<style lang="scss">
.album-dialog-form {
  width: 100%;
  margin-bottom: 10px;
}
</style>